package Q450;

/**
 * 删除二叉搜索树中的结点
 * @author 23737
 * @time 2021.12.11
 */
public class Test {
    public static void main(String[] args) {

    }
}

 class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode() {}
    TreeNode(int val) { this.val = val; }
    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

/**
 * 递归
 */
class Solution {
    public TreeNode deleteNode(TreeNode root, int key) {
        if(root == null){
            return null;
        }
        return helper(root, key);
    }
    public TreeNode helper(TreeNode root, int key){
        if(root == null){
            return null;
        }
        if(root.val > key){
            root.left  = helper(root.left, key);
        }else if(root.val < key){
            root.right = helper(root.right, key);
        }else{
            if(root.left == null){
                return root.right;
            }else if(root.right == null){
                return root.left;
            }
            TreeNode node = root.right;
            while(node.left != null){
                node = node.left;
            }
            root.val = node.val;
            root.right = helper(root.right, node.val);
        }
        return root;
    }
}
